package com.care.controller.admin.community;

import com.alibaba.fastjson.JSONObject;
import com.care.author.AuthRequired;
import com.care.controller.vo.JsonResult;
import com.care.dao.mapper.CommunityMapper;
import com.care.dao.mapper.InformationMapper;
import com.care.dao.mapper.ServiceMapper;
import com.care.dao.mapper.UserMapper;
import com.care.dao.model.*;
import com.care.service.ServiceInterface;
import com.care.utils.page.PageView;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.WebRequest;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

import jakarta.servlet.http.HttpServletRequest;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 后台社区管理员api：服务管理
 * @author xujinnan
 *
 */
@RequestMapping("/admin/community")
@RestController
public class ManagerServiceApi {

    @Autowired
    private ServiceMapper serviceMapper;

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private CommunityMapper communityMapper;

    /**
     * 社区仪表盘数据
     * @param request
     * @return
     */
    @RequestMapping("dashboard/data")
    @AuthRequired
    public JsonResult dashboardData(HttpServletRequest request) {
        JsonResult result = new JsonResult(true, "0", "查询成功");
        PageView<Service> pageView = new PageView<>();
        Admin manager = (Admin) request.getAttribute("loginAdmin");//当前登录的社区管理员
        //社区注册老人数量
        int ucount = userMapper.selectCommunityElderCount(manager.getCommunityId());
        //待处理服务请求数
        int wcount = serviceMapper.selectCommunityServiceCount(manager.getCommunityId(), ServiceInterface.SERVICE_STATUS_WAIT);
        //累计处理服务数
        int fcount = serviceMapper.selectCommunityFiniServiceCount(manager.getCommunityId());
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("ucont", ucount);
        jsonObject.put("wcount", wcount);
        jsonObject.put("fcount", fcount);
        result.setData(jsonObject);
        return result;
    }
    /**
     * 查询我的社区服务列表
     * @param request
     * @return
     */
    @RequestMapping("service/list")
    @AuthRequired
    public JsonResult communityService(HttpServletRequest request, PageView<Service> pageView, Integer status) {
        Admin manager = (Admin) request.getAttribute("loginAdmin");//当前登录的社区管理员
        Example example = new Example(Service.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("communityId", manager.getCommunityId());
        if(status != null){
            criteria.andEqualTo("status", status);
        }
        example.orderBy("publishTime").desc();
        List<Service> list = serviceMapper.selectByExampleAndRowBounds(example, new RowBounds(pageView.getFirstResult(), pageView.getMaxresult()));
        // 切割图片
        for (Service item : list) {
            if(StringUtils.isNotBlank(item.getPics())) {
                String[] url = item.getPics().split(",");
                List<String> urls = new ArrayList<>();
                for (int i=0; i<url.length; i++) {
                    urls.add(url[i]);
                }
                item.setPicList(urls);
            }
            item.setPublishUser(userMapper.selectByPrimaryKey(item.getUserId()));
            if(item.getStatus()>ServiceInterface.SERVICE_STATUS_WAIT){
                item.setVolunteer(userMapper.selectByPrimaryKey(item.getAcceptUserId()));
            }
        }
        pageView.setRecords(list);
        pageView.setTotalrecord(serviceMapper.selectCountByExample(example));//总记录数
        return JsonResult.success(pageView);
    }

    /**
     * 服务详情
     * @param sid
     * @return
     */
    @RequestMapping("service/detail")
    public JsonResult detail(@RequestParam Integer sid) {
        JsonResult result = new JsonResult(true, "0", "查询成功");
        Service service = serviceMapper.selectByPrimaryKey(sid);
        // 切割图片、标签
        if(StringUtils.isNotBlank(service.getPics())) {
            String[] url = service.getPics().split(",");
            List<String> urls = new ArrayList<>();
            for (int i=0; i<url.length; i++) {
                urls.add(url[i]);
            }
            service.setPicList(urls);
        }
        result.setData(service);
        return result;
    }

    /**
     * 取消服务
     * @param serviceId
     * @return
     */
    @RequestMapping("cancel")
    @AuthRequired
    public JsonResult cancelService(Integer serviceId){
        Service service = serviceMapper.selectByPrimaryKey(serviceId);
        service.setStatus(ServiceInterface.SERVICE_STATUS_CANCEL);
        serviceMapper.updateByPrimaryKeySelective(service);
        JsonResult jsonResult = new JsonResult();
        jsonResult.setData(service);
        return jsonResult;
    }

    /**
     * 服务反馈
     * @param req
     * @param request
     * @return
     */
    @RequestMapping("feedback")
    @AuthRequired
    public JsonResult feedbackService(@RequestBody JSONObject req, HttpServletRequest request){
        Integer serviceId = req.getInteger("serviceId");//
        Service service = serviceMapper.selectByPrimaryKey(serviceId);
        service.setFeedbackRate(req.getInteger("rate"));//反馈评分
        service.setFeedback(req.getString("feedback"));//反馈内容
        service.setStatus(ServiceInterface.SERVICE_STATUS_FEEDBACK);//完成反馈状态
        serviceMapper.updateByPrimaryKeySelective(service);//更新数据库
        JsonResult jsonResult = new JsonResult();
        jsonResult.setData(service);
        return jsonResult;
    }
}
